<template>
	<view class="pb-safe-area">
		<view class="p-4 flex flex-column grid-gap-4 mb-6" v-if="ing.length > 0">
			<view class="flex flex-column grid-gap-2">
				<text class="font-weight-600 h9 text-white">正在生成({{ ing.length }})</text>
				<text class="h10 text-placeholder">时间较久请耐心等待，处理完成会通过消息推送通知</text>
			</view>
			<view class="flex grid-gap-4 bg-bg-grey rounded-4 p-4" v-for="(item, index) in ing" :key="index">
				<view class="flex flex-center bg-placeholder rounded-4" style="width: 80px;height: 80px;"
					v-if="item.image" @tap="previewImage(item)">
					<image :src="item.image" mode="scaleToFill" class="rounded-4" style="width: 80px;height: 80px;" />
				</view>
				<view class="flex flex-center bg-placeholder rounded-4" style="width: 80px;height: 80px;" v-else>
					<uni-icons type="font" size="26" color="#191919" class="font-weight-600"></uni-icons>
				</view>
				<view class="flex-1 flex flex-column flex-x-space-between">
					<view class="flex grid-gap-2 flex-center">
						<text class="h10 font-weight-600 text-FEDFB4">ID:{{ item.id }}</text>
						<view class="flex-1 h9 text-ellipsis-2 font-weight-600 text-white"
							style="max-height:36px;line-height: 18px;">{{ item.prompt }}</view>
						<view class="bg rounded-round h10 py-1 px-4 text-placeholder" v-if="item.is_cancel"
							@tap="cancelItem(item)">取消</view>
					</view>
					<view class="flex flex-column grid-gap-4">
						<view class="bg rounded" style="height: 4px;">
							<view class="rounded" :class="{ 'bg-FEDFB4': item.is_vip, 'bg-white': !item.is_vip }"
								style="height: 4px;" :style="{ width: `${item.progress}%` }"></view>
						</view>
						<view class="flex grid-gap-2">
							<text class="h10 text-primary" v-if="item.state === 2">检测中</text>
							<text class="h10 text-FEDFB4" v-else-if="item.is_vip||USERINFO?.vip_state">VIP快速通道处理中</text>
							<text class="h10 text-FEDFB4" v-else @tap="showVip">开通{{ WEBCONFIG?.vip_name }}加速</text>
							<text class="h10 text-placeholder" v-if="item.wait_time > 0">预计等待{{ getTimeText(item.wait_time)
								}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="p-4 flex flex-column grid-gap-4" v-if="result.length > 0 || ing.length > 0">
			<view class="flex flex-column grid-gap-2">
				<text class="font-weight-600 h9 text-white">生成记录</text>
				<text class="h10" :class="{'text-FEDFB4':USERINFO?.vip_state,'text-placeholder':!USERINFO?.vip_state}">生成记录会为您保留 {{ USERINFO?.vip_state ? '30' : '7' }}天，请及时下载</text>
			</view>
			<view class="flex grid-gap-4 bg-bg-grey rounded-4 p-4" v-for="(item, index) in result" :key="index">
				<view class="flex flex-center bg-placeholder rounded-4" style="width: 80px;height: 80px;"
					v-if="item.image" @tap="previewImage(item)">
					<image :src="item.image" mode="scaleToFill" class="rounded-4" style="width: 80px;height: 80px;" />
				</view>
				<view class="flex flex-center bg-placeholder rounded-4" style="width: 80px;height: 80px;" v-else>
					<uni-icons type="font" size="26" color="#191919" class="font-weight-600"></uni-icons>
				</view>
				<view class="flex-1 flex flex-column flex-x-space-between">
					<view class="flex grid-gap-2 flex-center">
						<text class="h10 font-weight-600 text-FEDFB4">ID:{{ item.id }}</text>
						<view class="flex-1 h9 text-ellipsis-2 font-weight-600 text-white"
							style="max-height:36px;line-height: 18px;">{{ item.prompt }}</view>
						<view class="bg rounded-round h10 p-1" @tap="deleteItme(item)">
							<uni-icons type="closeempty" size="14" color="var(--xl-placeholder)"></uni-icons>
						</view>
					</view>
					<view class="flex">
						<text class="text-success h10" v-if="item.state === 1">已完成</text>
						<text class="text-danger h10" v-else-if="item.state === 99">失败</text>
					</view>
					<view class="flex flex-y-center grid-gap-2" v-if="item.state === 99">
						<uni-icons type="info-filled" size="14" color="var(--xl-danger)"></uni-icons>
						<text class="text-danger h10">{{ item.message }}</text>
					</view>
					<view class="flex flex-center">
						<text class="h10 flex-1 text-placeholder">{{ item.create_at }}</text>
						<view class="bg-primary rounded-round h10 py-1 px-4 text-white" @tap="preview(item)"
							v-if="item.state === 1">
							预览</view>
						<view class="bg rounded-round h10 py-1 px-4 text-white" @tap="retry(item)"
							v-else-if="item.state === 99">重试</view>
					</view>
				</view>
			</view>
		</view>
        <view v-if="result.length <=0 && ing.length<=0" class="vh-50 flex flex-center flex-column">
            <image src="@/static/empty.png" style="width:120px;height: 120px;" />
            <view class="text-primary-light-1 mt-2">暂无创作记录~</view>
        </view>
		<x-tabbar page="pages/record/index" />
		<x-popup v-model="showPreview" top="30vh" auto-hide-tab-bar>
			<view class="p-4 flex grid-gap-2 flex-center">
				<text class="h10 font-weight-600 text-FEDFB4">ID:{{ find.id }}</text>
				<view class="h9 text-ellipsis-2 font-weight-600 text-white" style="max-height:36px;line-height: 18px;">
					{{ find.prompt }}</view>
			</view>
			<view class="flex-1 flex flex-center">
				<video :src="find.video_url" style="width: 100vw;height: 80vw;"></video>
			</view>
			<view class="pb-safe-area">
				<view class="p-4">
					<view class="flex flex-center rounded-round py-6 bg-primary text-white" @tap="download">
						<text class="font-weight-600 h9">下载</text>
					</view>
				</view>
			</view>
		</x-popup>
		<x-vip ref="xVipRef" @success="" auto-hide-tab-bar />
	</view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { $http, $page, $message } from '@/utils';
import { onShow, onShareAppMessage, onShareTimeline, onPullDownRefresh } from "@dcloudio/uni-app";
import { useUserStore,useWebConfigStore, useRefs } from '@/stores';
const webConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(webConfigStore);
const userStore = useUserStore();
const { USERINFO } = useRefs(userStore);
const ing = ref([]);
const result = ref([]);
const showPreview = ref(false);
const xVipRef = ref();
const find = ref({});
const getList = () => {
	$http.get('Generation/record', {
	}).then((res: any) => {
		if (res.code === $http.ResponseCode.SUCCESS) {
			ing.value = res.data.ing;
			result.value = res.data.result;
		}
	}).finally(() => {
		uni.stopPullDownRefresh();
	})
}
const preview = (item: any) => {
	find.value = item;
	showPreview.value = true;
}
const download = () => {
	if (find.value.video_path) {
		uni.showLoading({
			title: '下载中...',
			mask: true
		})
		uni.downloadFile({
			url: find.value.download_video_url,
			success: (res) => {
				uni.hideLoading();
				uni.saveVideoToPhotosAlbum({
					filePath: res.tempFilePath,
					success: () => {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						})
					},
					fail: () => {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						})
					}
				})
			},
			fail: () => {
				uni.hideLoading();
				uni.showToast({
					title: '下载失败',
					icon: 'none'
				})
			},
		})
	} else {
		uni.showLoading({
			title: '远程下载中...',
			mask: true
		})
		$http.post('Generation/download', {
			data: {
				id: find.value.id
			}
		}).then((res: any) => {
			uni.hideLoading();
			if (res.code === $http.ResponseCode.SUCCESS) {
				find.value.video_path = res.data.path;
				find.value.download_video_url = res.data.url;
				download();
			} else {
				$message.error(res.msg);
			}
		}).catch(() => {
			uni.hideLoading();
		})
	}
}
const deleteItme = (item: any) => {
	uni.showModal({
		title: '提示',
		content: '确定删除该记录吗？',
		success: (res) => {
			if (res.confirm) {
				uni.showLoading({
					title: '删除中...',
					mask: true
				})
				$http.post('Generation/delete', {
					data: {
						id: item.id
					}
				}).then((res: any) => {
					if (res.code === $http.ResponseCode.SUCCESS) {
						getList();
					} else {
						$message.error(res.msg);
					}
				}).finally(() => {
					uni.hideLoading();
				})
			}
		}
	})
}
const cancelItem = (item: any) => {
	uni.showModal({
		title: '提示',
		content: '确定取消该生成任务吗？',
		success: (res) => {
			if (res.confirm) {
				uni.showLoading({
					title: '取消中...',
					mask: true
				})
				$http.post('Generation/cancel', {
					data: {
						id: item.id
					}
				}).then((res: any) => {
					if (res.code === $http.ResponseCode.SUCCESS) {
						getList();
					} else {
						$message.error(res.msg);
					}
				}).finally(() => {
					uni.hideLoading();
				})
			}
		}
	})
}
const getTimeText = (t: number) => {
	let text = '';
	let h = 0, hText = '';
	if (t > 3600) {
		h = Math.floor(t / 3600);
		hText = `${h}小时`;
		t = t % 3600
	}
	const m = Math.floor(t / 60).toString().padStart(2, '0');
	const s = Math.ceil(t % 60).toString().padStart(2, '0');
	text = `${hText}${m}分${s}秒`
	return text;
}
const retry = (item: any) => {
	uni.showLoading({
		title: '重试中...',
		mask: true
	})
	$http.post('Generation/retry', {
		data: {
			id: item.id
		}
	}).then((res: any) => {
		uni.hideLoading();
		if (res.code === $http.ResponseCode.SUCCESS) {
			getList();
		} else {
			$message.error(res.msg);
		}
	}).catch(() => {
		uni.hideLoading();
	})
}
const previewImage = (item: any) => {
	uni.previewImage({
		urls: [item.image]
	})
}
const showVip = () => {
	xVipRef.value.show();
}
onShow(() => {
	getList();
})
onPullDownRefresh(() => {
	getList();
})
onShareAppMessage(() => {
	return $page.shareMessage({
		title: '',
		path: `/pages/index/index`
	})
})
onShareTimeline(() => {
	return $page.shareTimeline({
		title: '',
		path: `/pages/index/index`
	})
})
</script>

<style>
.text-FEDFB4 {
	color: #FEDFB4;
}

.bg-FEDFB4 {
	background-color: #FEDFB4;
}
</style>
